package col

import (
	"yunj/pkg/yunj/core/builder/builderconsts"
	tableConsts "yunj/pkg/yunj/core/builder/builderconsts"
	"yunj/pkg/yunj/core/builder/table"
	"yunj/pkg/yunj/core/builder/table/col/action"
)

// 操作栏
type Action struct {
	table.Col
	Options []action.ActionInterface `json:"options"` // 操作项
}

func NewAction(title string, field ...string) *Action {
	c := &Action{}
	// 设置默认值
	c.Type = tableConsts.TABLE_COL_TYPE_NORMAL

	table.SetColInstance(&c.Col, c)
	if len(field) <= 0 {
		field = []string{builderconsts.TABLE_COL_ACTION_FIELD}
	}
	c.SetColField(field[0])
	c.SetTitle(title)
	c.Options = []action.ActionInterface{}
	return c
}

// 设置标题
func (c *Action) SetTitle(title string) *Action {
	c.Title = title
	return c
}

// 设置排列方式
func (c *Action) SetAlign(align string) *Action {
	c.Align = align
	return c
}

// 设置固定列
func (c *Action) SetFixed(fixed string) *Action {
	c.Fixed = fixed
	return c
}

// 设置隐藏列
func (c *Action) SetHide(hide string) *Action {
	c.Hide = hide
	return c
}

// 设置宽度
func (c *Action) SetWidth(width any) *Action {
	c.Width = width
	return c
}

// 设置最小宽度
func (c *Action) SetMinWidth(minWidth uint64) *Action {
	c.MinWidth = minWidth
	return c
}

// 设置最大宽度
func (c *Action) SetMaxWidth(maxWidth uint64) *Action {
	c.MaxWidth = maxWidth
	return c
}

// 设置权限
func (c *Action) SetAuth(auth string) *Action {
	c.Auth = auth
	return c
}

// 设置操作项
func (c *Action) SetOptions(options []action.ActionInterface) *Action {
	c.Options = options
	return c
}

// 处理属性
func (c *Action) HandleAttr() (err error) {
	if c.Align == "" {
		c.Align = builderconsts.ALIGN_CENTER
	}
	if c.Fixed == "" {
		c.Fixed = tableConsts.TABLE_COL_FIXED_RIGHT
	}
	// 操作项
	var hasAuth bool
	options := make([]action.ActionInterface, 0, len(c.Options))
	for _, option := range c.Options {
		hasAuth, err = option.RenderHandle(c.GinContext, c.BuilderId)
		if err != nil {
			return
		}
		// 没有权限
		if !hasAuth {
			continue
		}
		options = append(options, option)
	}
	c.Options = options
	return nil
}

// 是否渲染判断
func (c *Action) IsRenderCheck() bool {
	return len(c.Options) > 0
}
